﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using System.Diagnostics;
using Microsoft.Win32;
using System.ServiceProcess;
using System.Threading;
using System.Net.NetworkInformation;

namespace KengeeIT_ShopApp_Main
{
    public partial class FrmShopAppMain : Form
    {
        SqlConnection _SqlConnection;
        IPAddress[] IPAddress;
        string FilePath_MP3List = "C:\\KenGeeMP3List.xml";
        string DirPath_ShopMP3 = "D:\\仟吉音乐\\";
        DataTable dtMP3List;

        delegate void dgUpdateProgress(ProgressBar pbCurrent, int iPercent);
        public void pUpdateProgress(ProgressBar pbCurrent, int iPercent)
        {
            pbCurrent.Value = iPercent;
            pbCurrent.Refresh();
        }

        delegate void dgCloseTimer(bool aEnable);
        public void pCloseTimer(bool aEnable)
        {
            timer1.Enabled = aEnable;
        }

        delegate void dgMP3State(string aState);
        public void pMP3State(string aState)
        {
            lblMP3State.Text = aState;
        }

        //delegate void dgdgvMusicListAdd(string MusicName,string FilePath);
        //public void pdgvMusicListAdd(string MusicName,string FilePath)
        //{
        //    dgvMusicList.Rows.Add(MusicName, FilePath);
        //}

        public FrmShopAppMain(SqlConnection scn)
        {
            InitializeComponent();
            _SqlConnection = scn;
            string PCName = Dns.GetHostName();
            IPAddress = Dns.GetHostAddresses(PCName);
            this.Text += ":" + IPAddress[0];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string ms = "本地主机名：" + Dns.GetHostName() + "\r\n";
            for (int i = 0; i < IPAddress.Length; i++)
            {
                ms += "本地IP地址["+i.ToString()+"]:"+IPAddress[i].ToString() + "\r\n";
            }
            MessageBox.Show(ms);
        }

        private int UpdateTime_ShopConnect(string aID)
        {
            int result = -1;
            string sql = @"UPDATE [kengee_it_mis].[dbo].[ShopConnect]
                                   SET [ConnectTime] = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + @"'
                                 WHERE (ID='" + aID + "')";
            try
            {

                SqlCommand scmShopConneect = _SqlConnection.CreateCommand();
                scmShopConneect.CommandText = sql;
                _SqlConnection.Open();
                result = scmShopConneect.ExecuteNonQuery();
                _SqlConnection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.UpdateTime_ShopConnect;\r\naID=" + aID + ";\r\n" + ex.ToString());
            }
            finally
            {
                _SqlConnection.Close();
            }
            return result;
        }

        private int InsertTime_ShopConnect(string IPAddress, string aConnectProject)
        {
            int result = -1;
            string sql = @"INSERT INTO [kengee_it_mis].[dbo].[ShopConnect]
                               ([IPAddress]
                               ,[ConnectTime]
                               ,[ConnectProject]
                                ,[ConnectState])
                         VALUES
                               ('" + IPAddress + @"'
                               ,'" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + @"'
                               ,'" + aConnectProject + @"'
                               ,'正在进行')";
            try
            {

                SqlCommand scmShopConneect = _SqlConnection.CreateCommand();
                scmShopConneect.CommandText = sql;
                _SqlConnection.Open();
                result = scmShopConneect.ExecuteNonQuery();
                _SqlConnection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.InsertTime_ShopConnect;\r\nIPAddress=" + IPAddress + ";\r\naConnectProject=" + aConnectProject + ";\r\nsql=" + sql + ";\r\n" + ex.ToString());
            }
            finally
            {
                _SqlConnection.Close();
            }
            return result;
        }

        private int Delete_ShopConnect(string aIPAddress, string aConnectProject)
        {
            int result = -1;
            string sql = @"UPDATE [kengee_it_mis].[dbo].[ShopConnect]
                                   SET [ConnectState] = '下载完成'
                                        ,[OverTime]='" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + @"' 
                              WHERE (ConnectState='正在进行') and (IPAddress='" + aIPAddress + "') and (ConnectProject='" + aConnectProject + "')";

            try
            {

                SqlCommand scmShopConneect = _SqlConnection.CreateCommand();
                scmShopConneect.CommandText = sql;
                _SqlConnection.Open();
                result = scmShopConneect.ExecuteNonQuery();
                _SqlConnection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.Delete_ShopConnect;\r\nIPAddress=" + IPAddress + ";\r\naConnectProject=" + aConnectProject + ";\r\nsql=" + sql + ";\r\n" + ex.ToString());
            }
            finally
            {
                _SqlConnection.Close();
            }
            return result;
        }

        private int GetMaxConnect()
        {
            int result = -1;
            string sql = @"SELECT Value FROM ConstantValue where (TableName='ShopConnect') and (FieldName='MP3MaxConnect')";
            try
            {
                SqlCommand cmd = _SqlConnection.CreateCommand();
                cmd.CommandText = sql;
                _SqlConnection.Open();
                result = Convert.ToInt32(cmd.ExecuteScalar()); //从数据库中取到的Image类型的字段的值，转换成byte[]类型
                _SqlConnection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.GetMaxConnect;\r\nsql=" + sql + ";\r\n" + ex.ToString());
            }
            finally
            {
                _SqlConnection.Close();
            }
            return result;
        }

        private bool FindFromDataTable(DataTable aDataTable, string aColumnName, string KeyValue,out int RowIndex)
        {
            bool result = false;
            RowIndex = -1;
            for (int i = 0; i < aDataTable.Rows.Count; i++)
            {
                if (aColumnName.Trim().Length > 0)
                {
                    string DBValue = aDataTable.Rows[i][aColumnName].ToString();
                    if (DBValue.Contains(KeyValue))
                    {
                        RowIndex = i;
                        result = true;
                        break;
                    }
                }
                else
                {
                    for (int j = 0; j < aDataTable.Columns.Count; j++)
                    {
                        string DBValue = aDataTable.Rows[i][j].ToString();
                        if (DBValue.Contains(KeyValue))
                        {
                            RowIndex = i;
                            result = true;
                            break;
                        }
                    }
                }
            }
            return result;
        }

        private bool CanDownload()
        {
            bool result = false;
            try
            {                
                lblMP3State.Text = "正在判断下载许可...";
                string sql = @"SELECT [ID]
                                      ,[IPAddress]
                                      ,[ConnectTime]
                                      ,[ConnectProject]
                                      ,[ConnectState]
                                      ,[OverTime]
                                  FROM [kengee_it_mis].[dbo].[ShopConnect]
                                    where ConnectState='正在进行'";
                SqlDataAdapter sdaShopConnect = new SqlDataAdapter(sql, _SqlConnection);
                DataTable dtShopConnect = new DataTable();
                _SqlConnection.Open();
                sdaShopConnect.Fill(dtShopConnect);
                _SqlConnection.Close();
                sdaShopConnect.Dispose();

                //是否存在有
                int aRowIndex=-1;
                int iMaxConnect = GetMaxConnect();
                if (FindFromDataTable(dtShopConnect, "IPAddress", IPAddress[0].ToString(), out aRowIndex))
                {
                    string ID = dtShopConnect.Rows[aRowIndex]["ID"].ToString();
                    UpdateTime_ShopConnect(ID);
                    result = true;
                }
                else if (dtShopConnect.Rows.Count < iMaxConnect)
                {
                    InsertTime_ShopConnect(IPAddress[0].ToString(), "下载MP3");
                    result = true;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.CanDownload;\r\n" + ex.ToString());
            }
            return result;
        }

        private void btnGetMP3_Click(object sender, EventArgs e)
        {
            btnGetMP3.Enabled = false;
            if (_SqlConnection != null)
            {
                lblMP3State.Text = "正在连接服务器...";
                timer1.Interval = 3600000;
                //timer1.Interval = 3000;
                timer1.Enabled = true;
                timer1_Tick(null, null);
            }
            else
            {
                MessageBox.Show("服务器无法访问，放弃仟吉音乐MP3下载");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string CurrentPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\";
            cs_autoupdate_server.ClassFile cfFile = new cs_autoupdate_server.ClassFile(CurrentPath + "KengeeIT_ShopApp_Main.dll", "ShopApp", _SqlConnection);

            lblVersion.Text = "(版本号：" + cfFile.Version + ")";
            wmpMP3.currentPlaylist = wmpMP3.newPlaylist("KenGeeMP3List", "");
            wmpMP3.settings.setMode("loop", true);


            if (File.Exists(FilePath_MP3List))
            {
                dgvMusicList.Columns.Clear();
                dtMP3List = ClassDB.DBTrans.XML2dgv(FilePath_MP3List, dgvMusicList);
                SetWMPCurrentPlayList(wmpMP3, dgvMusicList);
                lblMP3State.Text = "状态信息：MP3播放列表载入完成！";
            }
            else
            {
                dtMP3List = new DataTable();
                dtMP3List.Columns.Add("歌名");
                dtMP3List.Columns.Add("路径");
                dgvMusicList.DataSource = dtMP3List;
            }
        }

        private void LoadMP3()
        {
            string sql = @"SELECT DISTINCT [ProjectName]
                                  ,[FileName]
                              FROM [kengee_it_mis].[dbo].[ProgramFile] 
                                where ProjectName='MP3'";
            DataTable dtMP3File = new DataTable();
            try
            {
                SqlDataAdapter sdaMP3File = new SqlDataAdapter(sql, _SqlConnection);
                _SqlConnection.Open();
                sdaMP3File.Fill(dtMP3File);
                _SqlConnection.Close();
                sdaMP3File.Dispose();

               
                DataTable dtNew = new DataTable();
                if (File.Exists(FilePath_MP3List))
                {
                    dtNew.ReadXml(FilePath_MP3List);
                }
                else
                {
                    dtNew.Columns.Add("歌名");
                    dtNew.Columns.Add("路径");
                    dtNew.TableName = "dgvMusicList";
                }

                for (int i = 0; i < dtMP3File.Rows.Count; i++)
                {
                    string FilePath = DirPath_ShopMP3 + dtMP3File.Rows[i]["FileName"].ToString();
                    if (File.Exists(FilePath) == false)
                    {
                        cs_autoupdate_server.ClassFile cfMP3 = new cs_autoupdate_server.ClassFile(FilePath, "MP3", _SqlConnection);
                        cfMP3.DownloadFile();
                        dtNew.Rows.Add(dtMP3File.Rows[i]["FileName"].ToString(), FilePath);
                        //this.BeginInvoke(new dgdgvMusicListAdd(pdgvMusicListAdd), dtMP3File.Rows[i]["FileName"].ToString(), FilePath);
                    }
                    this.BeginInvoke(new dgUpdateProgress(pUpdateProgress), progressBar1, i * 100 / dtMP3File.Rows.Count);
                }
                this.BeginInvoke(new dgUpdateProgress(pUpdateProgress), progressBar1, 100);
                this.BeginInvoke(new dgCloseTimer(pCloseTimer), false);
                this.BeginInvoke(new dgMP3State(pMP3State), "MP3下载完成！");
                Delete_ShopConnect(IPAddress[0].ToString(), "下载MP3");
                MessageBox.Show("仟吉音乐MP3下载完成");

                File.Delete(FilePath_MP3List);
                dtNew.WriteXml(FilePath_MP3List, System.Data.XmlWriteMode.WriteSchema);
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=FrmShopAppMain.LoadMP3;\r\nsql=" + sql + ";\r\n" + ex.ToString());
            }
            finally
            {
                _SqlConnection.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            SetRegistry("0");
        }

        private void SetRegistry(string aValue)
        {
            RegistryKey rkCurrentUser = Registry.CurrentUser;
            RegistryKey rkSoftware = rkCurrentUser.CreateSubKey("Software");
            RegistryKey rkPolicies = rkSoftware.CreateSubKey("Policies");
            RegistryKey rkMicrosoft = rkPolicies.CreateSubKey("Microsoft");
            RegistryKey rkWindows = rkMicrosoft.CreateSubKey("Windows");
            RegistryKey rkNC = rkWindows.CreateSubKey("Network Connections");
            rkNC.SetValue("NC_EnableAdminProhibits", "1", RegistryValueKind.DWord);
            rkNC.SetValue("NC_LanConnect", aValue, RegistryValueKind.DWord);//禁止停用网卡
            rkNC.SetValue("NC_AllowAdvancedTCPIPConfig", aValue, RegistryValueKind.DWord);//禁止TCP协议高级选项
            rkNC.SetValue("NC_AddRemoveComponents", aValue, RegistryValueKind.DWord);//禁止安装和卸载网络协议
            rkNC.SetValue("NC_ChangeBindState", aValue, RegistryValueKind.DWord);//禁止启用和停止网络协议
            rkNC.SetValue("NC_LanChangeProperties", aValue, RegistryValueKind.DWord);//禁止访问网络议属性
            rkNC.SetValue("NC_RenameConnection", aValue, RegistryValueKind.DWord);//禁止重命名网卡
        }

        private void lblVersion_DoubleClick(object sender, EventArgs e)
        {
            SetRegistry("1");                            
        }

        private void btnPCAnyWhere_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceController _svctPCAnyWhere = new ServiceController();                
                _svctPCAnyWhere.ServiceName = "awhost32";                

                if ((_svctPCAnyWhere.Status == ServiceControllerStatus.Paused)
                    || (_svctPCAnyWhere.Status == ServiceControllerStatus.Stopped))
                {
                    _svctPCAnyWhere.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("function=btnPCAnyWhere_Click;\r\n" + ex.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (CanDownload())
            {
                //创建目录
                string DirName = "D:\\仟吉音乐";
                if (Directory.Exists(DirName) == false)
                {
                    Directory.CreateDirectory(DirName);
                }
                lblMP3State.Text = "正在下载MP3文件...";
                Thread myThread = new Thread(LoadMP3);
                myThread.Start();
            }
            else
            {
                lblMP3State.Text = "正在等待获取下载许可...";
            }
        }

        private void FrmShopAppMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "MP3文件|*.MP3|全部文件|*.*";
            ofd.InitialDirectory = DirPath_ShopMP3;
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < ofd.SafeFileNames.Length; i++)
                {
                    if (ClassDB.DBFind.FindRow(dgvMusicList, "歌名", ofd.SafeFileNames[i])==false)
                    {
                        dtMP3List.Rows.Add(ofd.SafeFileNames[i], ofd.FileNames[i]);
                        WMPLib.IWMPMedia MediaAppend = wmpMP3.newMedia(ofd.FileNames[i]);
                        wmpMP3.currentPlaylist.appendItem(MediaAppend);
                    }
                }
                dgvMusicList.DataSource = dtMP3List;
                ClassDB.DBTrans.dgv2XML(dgvMusicList, FilePath_MP3List);
            }
            //wmpMP3.currentPlaylist.clear();
            //SetWMPCurrentPlayList(wmpMP3, dgvMusicList);
            lblMP3State.Text = "状态信息：MP3播放列表添加完成！";
        }

        private void SetWMPCurrentPlayList(AxWMPLib.AxWindowsMediaPlayer aWindowsMediaPlayer, DataGridView dgv)
        {
            wmpMP3.currentPlaylist = wmpMP3.newPlaylist("KenGeeMP3List", "");
            for (int i = 0; i < dgv.RowCount; i++)
            {
                string FilePath = dgvMusicList.Rows[i].Cells["路径"].Value.ToString();
                WMPLib.IWMPMedia MediaAppend = wmpMP3.newMedia(FilePath);
                wmpMP3.currentPlaylist.appendItem(MediaAppend);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            wmpMP3.currentPlaylist.clear();
            if (dgvMusicList.DataSource == null)
            {
                dgvMusicList.Rows.Clear();
            }
            else
            {
                DataTable dtMP3List = dgvMusicList.DataSource as DataTable;
                dtMP3List.Rows.Clear();
                dgvMusicList.DataSource = dtMP3List;
            }
            File.Delete(FilePath_MP3List);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dgvMusicList.SelectedRows.Count > 0)
            {
                while (dgvMusicList.SelectedRows.Count > 0)
                {
                    int SelIndex = dgvMusicList.SelectedRows[0].Index;
                    dgvMusicList.Rows.RemoveAt(SelIndex);
                    wmpMP3.currentPlaylist.removeItem(wmpMP3.currentPlaylist.get_Item(SelIndex));
                }
            }
            else
            {
                int CurIndex = dgvMusicList.CurrentRow.Index;
                dgvMusicList.Rows.RemoveAt(CurIndex);
                wmpMP3.currentPlaylist.removeItem(wmpMP3.currentPlaylist.get_Item(CurIndex));
            }
            ClassDB.DBTrans.dgv2XML(dgvMusicList, FilePath_MP3List);
        }

        private void button5_Click(object sender, EventArgs e)
        {            
            wmpMP3.Ctlcontrols.stop();
            wmpMP3.settings.mute = false;
            int TempIndex = dgvMusicList.CurrentRow.Index;
            wmpMP3.Ctlcontrols.currentItem = wmpMP3.currentPlaylist.get_Item(TempIndex);
            wmpMP3.Ctlcontrols.play();
            lblMP3State.Text = "状态信息：正在播放MP3：" + dgvMusicList.CurrentRow.Cells["歌名"].Value.ToString();
        }

        private void dgvMusicList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            btnMP3Play.PerformClick();
        }

        private void wmpMP3_CurrentItemChange(object sender, AxWMPLib._WMPOCXEvents_CurrentItemChangeEvent e)
        {
            string curURL = wmpMP3.currentMedia.sourceURL;
            ClassDB.DBFind.FindRowSetCurrent(dgvMusicList, "路径", curURL);
            lblMP3State.Text = "状态信息：正在播放MP3：" + dgvMusicList.CurrentRow.Cells["歌名"].Value.ToString();
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            wmpMP3.Ctlcontrols.stop();
            wmpMP3.currentPlaylist.clear();
            dgvMusicList.Columns.Clear();
            ClassDB.DBTrans.XML2dgv(FilePath_MP3List, dgvMusicList);
            SetWMPCurrentPlayList(wmpMP3, dgvMusicList);
            lblMP3State.Text = "状态信息：MP3播放列表载入完成！";
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string monitorIP = GetMonitorIP();
            if (PingHost(monitorIP))
            {
                Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", monitorIP);
            }
        }

        private string GetMonitorIP()
        {
            string result = string.Empty;
            int LastDotIndex = IPAddress[0].ToString().LastIndexOf(".");
            string monitorIP = IPAddress[0].ToString().Substring(0, LastDotIndex);
            result = monitorIP + ".10";
            return result;
        }

        private bool PingHost(string HostIP)
        {
            bool result = false;
            Ping pingSender = new Ping(); //Ping既然是类，为何不变色？
            PingReply reply = pingSender.Send(HostIP);
            if (reply.Status == IPStatus.Success)
            {
                result = true;
                //string message = string.Format("地址:{0}连接测试成功！", HostIP);
                //MessageBox.Show(message);
            }
            else
            {
                string message = string.Format("地址:{0}连接测试失败！", HostIP);
                MessageBox.Show(message);
            }
            return result;
        }
    }
}
